<?php
function encodeToUtf8($string) {
	return mb_convert_encoding($string, "UTF-8", mb_detect_encoding($string, "UTF-8, ISO-8859-8, ISO-8859-15", true));
}

function encodeToIso($string) {
	return mb_convert_encoding($string, "ISO-8859-8", mb_detect_encoding($string, "UTF-8, ISO-8859-8, ISO-8859-15", true));
}
/**
 * strip_selected_tags ( string str [, string strip_tags[, strip_content flag]] )
 * ---------------------------------------------------------------------
 * Like strip_tags() but inverse; the strip_tags tags will be stripped, not kept.
 * strip_tags: string with tags to strip, ex: "<a><p><quote>" etc.
 * strip_content flag: TRUE will also strip everything between open and closed tag
 */

function strip_selected_tags($str, $tags = "", $stripContent = false)
{
	preg_match_all("/<([^>]+)>/i",$tags,$allTags,PREG_PATTERN_ORDER);
	foreach ($allTags[1] as $tag){
		if ($stripContent) {
			$str = preg_replace("/<".$tag."[^>]*>.*<\/".$tag.">/iU","",$str);
		}
		$str = preg_replace("/<\/?".$tag."[^>]*>/iU","",$str);
	}
	return $str;
}
/**
 * changeRowToArrays -> sets a line of raw data to a recognized string of required data
 * of the form: $group@$semester@$day@$hourStart-$hourEnd@$courseName@$lecOrRec@$teacher@$location
 * if the value or lecOrRec is 0, the new string is added as a new cell to the lecsArr
 * if the value of lecOrRec is 1, the new string is added as a new cell to the recsArr
 *
 * @param string $rawData the raw text to be manipulated by the function 
 * @param char* $lecsArr pointer to the array of lecture strings
 * @param char* $recsArr pointer to the array of recitations strings
 * @param string $courseName nameof the course (might have spaces in it)
 */
function changeRowToArrays($rawData,&$lecsArr,&$recsArr,$semesterFilter)
{
	$courseArr = explode(" ",$courseName);
	$courseNameSize = sizeof($courseArr); // we start handleing the array from this number
	$temp = explode(" ",$rawData);
	$i = $courseNameSize - 1;
	//print("name size = $courseNameSize<br>");
	$j = $i + 3;
	$teacher = "";
	for ($i; $i<$j; ++$i) //the teacher is the next 3 cells on the array;
	{
		$teacher .="$temp[$i] ";
	}
	//finding out if its a recitation or a lecture
	$keyLecRec = array_search("שיעור",$temp);
	$lecOrRec;
	if(!$keyLecRec) //if not a lecture, then its a recitation
	{
		$keyLecRec = array_search("תרגיל",$temp);
		$lecOrRec = 1;
	}
	else
		$lecOrRec = 0; 
	//getting the index of the semester cell
	$keySemester = array_search("סמ'",$temp);
	$semester = $temp[$keySemester+1];
	$hourStart = substr($temp[$keySemester-1],0,2);
	$hourEnd = substr($temp[$keySemester-3],0,2);
	$day = getDay($temp[$keySemester-4]);
	//the location is between the lec/rec key and the day key
	$location = "";
	for ($i = ($keyLecRec+1); $i<($keySemester-4);++$i)
		$location .= "$temp[$i] ";
	$group = substr($temp[sizeof($temp)-1],10,2);
	//$toAdd = "$group@$day@$hourStart-$hourEnd@$courseName@$lecOrRec@$teacher@$location";
	$toAdd = "$group@$day@$hourStart-$hourEnd@$lecOrRec";
	//print "group=$group@sem=$semester@day=$day@hour=$hourStart-$hourEnd@name=$courseName@lec/rec=$lecOrRec@teach=$teacher@loc=$location<br>";
	if(0 == $lecOrRec && 0 == strcmp($semester,$semesterFilter) )
		array_push($lecsArr,$toAdd);
	else if (1 == $lecOrRec && 0 == strcmp($semester,$semesterFilter) )
		array_push($recsArr,$toAdd);
}
function getDay($hebDay)
{
	switch ($hebDay)
	{
		case "א'":
			return "a";
			break;
		case "ב'" :
			return "b";
			break;
		case "ג'":
			return "c";
			break;
		case "ד'":
			return "d";
			break;
		case "ה'":
			return "e";
			break;
		default :
			return "errorDay";
			break;
	}
}
/**
 * getHtmlPage -> gets the page displayed by the university after search params were inserted
 *
 */
function getHtmlPage()
{
	//debug : ?MfcISAPICommand=but&year=2007&course_num=03682157
	$argv = "MfcISAPICommand=$_GET[MfcISAPICommand]&year=$_GET[year]&course_num=$_GET[course_num]";
	//$argv = $_SERVER['QUERY_STRING']; //?bla=asd&bloo=dsa&x=5&y=24&bli=123&blo=fdfsd ->we are getting rid of x and y
	$url= "http://www2.tau.ac.il/yed/yednew.dll?$argv";
	//MfcISAPICommand=but&year=2007&department1=&department2=&department3=&department4=&department5=&department6=03680382&department7=&course_nam=&teach_nam=&department8=&department9=&department10=&x=12&y=15&department11=&department12=';
	$conn = fopen($url, "r");
	fclose($conn);
	return  file_get_contents($url);
}
/**
 * parseHtml -> cleans all garbage, sets encoding to utf8 and fixes hebrew to apear strait
 * will put in $html the text that is required for course data processing
 * will put in $htmlTestValues the text that is required for test data processing
  */
function parseHtml(&$html,&$htmlTestValues)
{
	$HEADER_SIZE = 2783 ; //size of chars to clean from header of html;
	//proccessing the html output
	$html = substr($html,$HEADER_SIZE); //removing all the header
	$html = strip_selected_tags($html,"<img><IMG><tr><TR>",true); //removing unimportant tags with whats inside
	$html = strip_selected_tags($html,"<th><TH><td><TD><map><body><html><div><table>",false); //removing unimportant tags but keeping whats inside
	$htmlTestValues = $html;
	$html = strip_selected_tags($html,"<a><A>",true);
	$html = str_replace("&nbsp;","",$html); // removing &nbsp from the text
	$html = preg_replace('/\s\s+/', ' ', $html); //removing white space from the text
	$html = hebrev($html); // fixing hebrew direction
	$html = encodeToUtf8($html); //converting the iso encoding to utf8 encoding
	$htmlTestValues = str_replace("&nbsp;","",$htmlTestValues);
	$htmlTestValues = preg_replace('/\s\s+/', ' ',$htmlTestValues);
	//$htmlTestValues = hebrev($htmlTestValues);
	$htmlTestValues = strtolower($htmlTestValues);
	$htmlTestValues = encodeToUtf8($htmlTestValues);
	
	
}
function getSiteLinks($parsedHtml)
{
	$a = array();
	if(preg_match_all('/<a\s+.*?href=[\"\']?([^\"\' >]*)[\"\']?[^>]*>(.*?)<\/a>/i',$parsedHtml,$matches,PREG_SET_ORDER))
	{
		foreach($matches as $match)
		{
			array_push($a,array($match[1],$match[2]));
		}
	}
	return $a;
}
function genereateSelectOptions($lecsArr,$recsArr,$courseName)
{
	$serial = $_GET['serial'];
	print "<div class=groupsLectureCell id=lecCell$serial>";
	print "<select name=lec$serial id=lec$serial class=inputSelect onChange=transmit(this,'lec')>";
	print "<option value=''>בחר</option>";
	for ($i = 0; $i<sizeof($lecsArr); ++$i)
	{
		print"<option value=\"$lecsArr[$i]\">".substr($lecsArr[$i],0,2)."</option>";
	}
	print "</select></div>";
	print "<div class=groupesRecCell id=recs$serial>";
	print "<select name=rec$serial id=rec$serial onChange=transmit(this,'rec')>";
	print "<option value=''>בחר</option>";
	for ($i = 0; $i<sizeof($recsArr); ++$i)
	{
		print "<option value=\"$recsArr[$i]\">".substr($recsArr[$i],0,2)."</option>";
	}
	print "</select>";
	print "<input type=hidden id=courseName$serial value='$courseName' />";
	print "</div>";
	
}

?>